package com.flyxiaozhu.erp.core.repositories;

import com.flyxiaozhu.erp.core.entities.Goods;
import org.springframework.data.jpa.repository.*;

import javax.persistence.LockModeType;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.List;

/**
 * @author flyxiaozhu
 * @date 2019-04-12 18:36
 */
public interface GoodsRepository extends JpaRepository<Goods, Long>, JpaSpecificationExecutor<Goods> {
    Boolean existsByGoodsNo(String goodsNo);

    @Query("select g from Goods g where g.id = ?1")
    @Lock(LockModeType.PESSIMISTIC_WRITE) // 悲观琐
    Goods findByIdOnLock(long id);

    Goods findByGoodsNo(String goodsNo);

    void deleteAllByIdIn(Collection ids);

    List<Goods> findByIdIn(Collection ids);

    @Query("select g.stock from  Goods g where id = ?1")
    Integer getStock(Long id);

    @Query("update Goods g set g.stock = g.stock - ?2 where g.id = ?1")
    @Modifying
    @Transactional
    void decStock(long id, int num);

    @Query("update Goods g set g.stock = g.stock + ?2 where g.id = ?1")
    @Modifying
    @Transactional
    void incStock(long id, int num);
}
